from flask import request, g, session
import os
import urllib2
from tools import logging
import time
import sys
import traceback

counter = 0


def get():
    if request.args.get('action') == 'setsession':
        if os.environ.get('VIRTUAL_ENV', '').startswith('F:'):
            role = request.args.get('role')
            session['wechatrole'] = role
            return 'setsessiondone'
        else:
            return 'not in local'
    if request.args.get('action') == 'getargs':
        test = request.args.getlist('test')[-1]
        print test
        return '%r' % test
    if request.args.get('action') == 'date':
        from leancloud import Object, Query
        from datetime import datetime, timedelta
        test = Query(Object.extend('Test')).descending('createdAt').first()
        content = ''
        content += 'Test:%s,%s<br/>' % (test.get('name'), test.created_at)
        content += 'DatetimeNow: %s<br/>' % datetime.now()
        content += 'DatetimeUTCNow: %s<br/>' % datetime.utcnow()
        content += '1 DaysTests: %s<br/>' % ([t.id for t in 
            Query(Object.extend('Test')).greater_than('createdAt', datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)).find()])
        return content
    if request.args.get('action') == 'savefile':
        # action=savefile&classname=Agm_Product&oname=img|img_td&nname=imgfile|imgfile_td&count=1
        classname = request.args.get('classname')
        oname = request.args.get('oname')
        nname = request.args.get('nname')
        if oname and '|' in oname:
            oname = oname.split('|')
            nname = nname.split('|')
        count = request.args.get('count')
        if count:
            count = int(count)
        if classname and oname and nname:    
            from tools.saveFile import saveFile
            saveFile(classname, oname, nname, count)
            return 'SaveFile Done'
        else:
            return 'Arguments Error'
    if request.args.get('action') == 'g': 
        global counter
        counter += 1
        if hasattr(g, 'counter'):
            g.counter += 1
        else:
            g.counter = 0
        from dbModels import selfCache
        if 'counter' in selfCache:
            selfCache['counter'] += 1
        else:
            selfCache['counter'] = 0
        content = 'Counter:%s<br/>\ng:%s<br/>\nselfCache:%s\n<br/>\n' % (counter, g.counter, selfCache['counter'])
        return content
    if request.args.get('action') == 'getip':
        return get_external_ip()
    if request.args.get('action') == 'fetch':
        url = request.args.get('url')
        url = url.replace('imfunimfun', '.')
        return urllib2.urlopen(url).read()
    if request.args.get('action') == 'error':
        int('a')
        return 'ErrorDone!'
    if request.args.get('action') == 'lxmltest':
        from lxml import etree
        return etree.XML('<test>haha</test>').text
        
    content = ''
    for i in ('content_type', 'data', 'path', 'full_path', 
        'pragma', 'url', 'query_string', 'args', 'remote_addr'):
        content += '%s:%s<br/>\n' % (i, getattr(request, i))

    content += 'X-Real-Ip: %s<br/>\n' % request.headers.get('X-Real-Ip')
    content += 'time.time():%s<br/>\n' % int(time.time())
    content += '%s<br/>\n'  % dir(request.headers)
    headers = dict(request.headers.items())
    notags = set()
    for t in headers:
        if 'X-Avoscloud' in t:
            notags.add(t)
    for t in notags:
        headers.pop(t)
    content += 'Headers: <pre>%s</pre><br/>\n' % headers
    print 'HelloWorld Test in Print'
    try:
        int('a')
    except:
        logging.error(traceback.format_exc())
        
    # logging.info(content)
    # logging.debug('Hello,World!')
    return content

def get_external_ip():
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        wechat_ip = socket.gethostbyname('api.mch.weixin.qq.com')
        sock.connect((wechat_ip, 80))
        addr, port = sock.getsockname()
        sock.close()
        return addr
    except socket.error:
        return '127.0.0.1'    
    
    
def log(content, log_error=False):
    if log_error:
        sys.stderr.write('ErrorFromlog():%s\n' % content)
    else:
        sys.stdout.write('InfoFromlog():%s\n' % content)
    
    